<?php

/**
 * 导购管理
 *
 * @author libaoling
 * @time 2014-12-5
 */
class Storeo2oApp extends BackendApp
{

    private $_storeo2o_mod;
    private $_storeo2olang_mod;
    private $_scategory_mod;
    private $_o2orecommend_mod;
    private $_o2oimage_mod;
    private $_language_mod;
    public $languages = array();

    public function __construct()
    {
        $this->Storeo2oApp();
    }

    public function Storeo2oApp()
    {
        parent::__construct();
        $this->_storeo2o_mod = & m('storeo2o');
        $this->_storeo2olang_mod = & m('storeo2olang');
        $this->_scategory_mod = m('scategory');
        $this->_o2orecommend_mod = m("o2orecommend");
        $this->_o2oimage_mod = m("o2ogoodsimage");
        $this->_language_mod = m("language");
        $this->languages = $this->_language_mod->get_list();
    }

    public function index()
    {
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'store_floor',
                'type' => 'int',
            ),
            array(
                'field' => 'products_search',
                'name' => 'products',
                'equal' => 'like',
            ),
            array(
                'field' => 'store_no',
                'equal' => 'like',
            ),
            array(
                'field' => 'store_name_search',
                'name' => 'store_name',
                'equal' => 'like',
            ),
        ));
        
        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
                $sort  = strtolower(trim($_GET['sort']));
                $order = strtolower(trim($_GET['order']));
                if (!in_array($order,array('asc','desc')))
                {
                        $sort  = 'sort_order';
                        $order = '';
                }
        }
        else
        {
                $sort  = 'store_id';
                $order = 'desc';
        }
        
        if(isset($_GET['is_wljiashi']) && $_GET['is_wljiashi'])
            $conditions .= $_GET['is_wljiashi'] == 1 ? " AND store_url != ''" : " AND store_url = ''";
        
        $floor_file = ROOT_PATH . '/includes/floor.inc.php';
        $floors = file_exists($floor_file) ? require $floor_file : array();

        $page = $this->_get_page(10);
        $stores = $this->_storeo2o_mod->findAll(array(
            'conditions' => '1 = 1 ' . $conditions,
            'include' => array('has_storeo2olang' => array('index_key' => array('store_id', 'lang'))),
            'fields' => 'store_no, add_time, store_floor, owner_name, enter_time, sort_order, recommended, exh_id',
            'order' => "$sort $order",
            'count' => true,
            'limit' => $page['limit'],
        ));
        
        $page['item_count'] = $this->_storeo2o_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign("stores", $this->_storeo2o_mod->remake_stores($stores));
        $this->assign("floors", $floors['all']);
        $this->import_resource(array('script' => 'inline_edit.js'));

        $this->display("storeo2o.index.html");
    }

    public function add()
    {
        if (!IS_POST)
        {
            /* 参数 */
            $floor_file = ROOT_PATH . '/includes/floor.inc.php';
            $floors = file_exists($floor_file) ? require $floor_file : array();
            $scategories = $this->_get_scategory();
            $images = $this->_o2oimage_mod->find(array(
                'conditions' => "store_id = 0",
            ));
            $this->assign("id", 0);
            $this->assign("belong", BELONG_O2OSTORE);
            $this->assign("images", $images);
            $this->assign('scategories', $scategories);
            $this->assign('floors', $floors['all']);
            $this->assign('languages', $this->languages);
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            
            $this->assign('build_upload', $this->_build_upload(array('upload_url' => 'index.php?app=swfupload&act=upload_o2o_image','belong' => BELONG_O2OSTORE, 'item_id' => 0))); // 构建swfupload上传组件
            $this->display('storeo2o.form.html');
        }
        else
        {
            $data = $this->_get_save_data();
            $data['add_time'] = time();
            $data['hot_image'] = $_POST['hot_image'];
            $data['feature_image'] = $_POST['feature_image'];
            $cate_ids = $this->_get_post_category_ids($_POST['sgcate_id']);

            if (!$store_id = $this->_storeo2o_mod->add($data))  //获取store_id
            {
                $this->show_warning($this->_storeo2o_mod->get_error());
                return;
            }

            if ($cate_ids)
            {
                $this->_storeo2o_mod->createRelation('has_scategory', $store_id, $cate_ids);
            }
            
            foreach ($this->languages as $key => $language)
            {
                if(isset($_POST['store_name'][$language['lang_id']])){
                    $this->_storeo2olang_mod->add(array(
                        'store_id' => $store_id,
                        'store_name' => trim($_POST['store_name'][$language['lang_id']]),
                        'products' => trim($_POST['products'][$language['lang_id']]),
                        'lang' => $language['lang_id'],
                    ), true);
                }
            }

            /* 处理上传的图片 */
            $this->_o2oimage_mod->edit("store_id=0", array("store_id" => $store_id));

            $this->admin_log('添加导购店铺:' . $store_id);
            $this->show_message('添加成功', 'back_list', 'index.php?app=storeo2o', 'continue_add', 'index.php?app=storeo2o&amp;act=add');
        }
    }

    public function edit()
    {
        $store_id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!IS_POST)
        {
            /* 参数 */
            $floor_file = ROOT_PATH . '/includes/floor.inc.php';
            $floors = file_exists($floor_file) ? require $floor_file : array();
            $scategories = $this->_get_select_scate($store_id);
            $store = $this->_storeo2o_mod->get_by_id($store_id);
            
            $images = $this->_o2oimage_mod->find(array(
                'conditions' => "store_id = {$store_id}",
            ));
            $this->assign('store', $store[$store_id]);
            $this->assign("id", $store_id);
            $this->assign("belong", BELONG_O2OSTORE);
            $this->assign("images", $images);
            $this->assign('scategories', $scategories);
            $this->assign('floors', $floors['all']);
            $this->assign('languages', $this->languages);
            $this->assign("act", "edit");
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            
            $this->assign('build_upload', $this->_build_upload(array('upload_url' => 'index.php?app=swfupload&act=upload_o2o_image','belong' => BELONG_O2OSTORE, 'item_id' => $store_id))); // 构建swfupload上传组件
            $this->display('storeo2o.form.html');
        }
        else
        {
            $data = $this->_get_save_data();
            $cate_ids = $this->_get_post_category_ids($_POST['sgcate_id']);
            $this->_storeo2o_mod->edit($store_id, $data);

            if ($cate_ids)
            {
                $this->_storeo2o_mod->unlinkRelation('has_scategory', $store_id);
                $this->_storeo2o_mod->createRelation('has_scategory', $store_id, $cate_ids);
            }
            
            foreach ($this->languages as $key => $language)
            {
                if(isset($_POST['store_name'][$language['lang_id']])){
                    $this->_storeo2olang_mod->add(array(
                        'store_id' => $store_id,
                        'lang' => $language['lang_id'],
                        'store_name' => trim($_POST['store_name'][$language['lang_id']]),
                        'products' => trim($_POST['products'][$language['lang_id']]),
                    ), true);
                }
            }

            $this->admin_log('修改导购店铺:' . $store_id);
            $this->show_message('修改成功', 'back_list', 'index.php?app=storeo2o');
        }
    }
    
    //异步修改数据
    public function ajax_col()
    {
        $id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $column = empty($_GET['column']) ? '' : trim($_GET['column']);
        $value  = isset($_GET['value']) ? trim($_GET['value']) : '';
        $data   = array();
        if (in_array($column ,array('recommended','sort_order','exh_id')))
        {
                $data[$column] = $value;
                $this->_storeo2o_mod->edit($id, $data);
                if(!$this->_storeo2o_mod->has_error())
                {
                        $this->admin_log("导购管理，店铺{$column}修改:id：{$id}");
                        echo ecm_json_encode(true);
                }
        }
        else
        {
                return ;
        }
        return ;
    }

    public function drop()
    {
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$id)
        {
            $this->show_warning('no_store_to_drop');
            return;
        }

        $ids = explode(',', $id);
        $this->admin_log('删除导购店铺:' . $id);

        foreach ($ids as $id)
        {
            $this->_drop_storeo2o_image($id);
            $this->_storeo2o_mod->unlinkRelation('has_scategory', $id);
        }

        if (!$this->_storeo2o_mod->drop($ids))
        {
            $this->show_warning($this->_storeo2o_mod->get_error());
            return;
        }
        
        $this->_storeo2olang_mod->drop($ids);
        $this->_o2orecommend_mod->drop("store_id = {$id}");

        $this->show_message('删除成功');
    }

    public function input_excel()
    {
        set_time_limit(0);
        $excel_array = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel');
        if ($_POST && $_FILES["inputExcel"]["tmp_name"])
        {
            if (!in_array($_FILES["inputExcel"]["type"], $excel_array))
            {
                $this->show_warning('请导入excel格式的文件');
                return;
            }

            require_once ROOT_PATH . '/includes/PHPExcel/PHPExcel.php';
            $stores = array();
            $scates = array();
            $excel = PHPExcel_IOFactory::load($_FILES["inputExcel"]["tmp_name"]);
            $data = $excel->getSheet(0)->toArray();
            unset($data[0]);
            $data = array_values($data);
            foreach ($data as $key => $item)
            {
                $stores[$key]['store_id'] = $item[0];
                $stores[$key]['lang'] = 2;
                $stores[$key]['store_name'] = addslashes(trim($item[4]));
                $stores[$key]['products'] = addslashes(trim($item[5]));
            }
            
            if ($stores)
            {
                $sql = "replace into wl_store_o2o_lang (store_id,lang,store_name,products) values ";
                foreach ($stores as $store)
                {
                    $sql .= "('{$store['store_id']}', '{$store['lang']}', '{$store['store_name']}', '{$store['products']}'),";
                }
                $sql = substr($sql, 0, -1);
                $this->_storeo2olang_mod->db->query($sql);
            }
        }
        header("Location:index.php?app=storeo2o");
    }

    public function check_store_no()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $store_no = empty($_GET['store_no']) ? '' : trim($_GET['store_no']);

        if (!$this->_storeo2o_mod->unique_store_no($store_no, $id))
        {
            echo ecm_json_encode(false);
            return;
        }
        echo ecm_json_encode(true);
    }

    /* 推荐商品到 */

    public function recommend()
    {
        if (!IS_POST)
        {
            /* 取得推荐类型 */
            $recommend_conf = ROOT_PATH . "/wl_admin/includes/config/o2o.recommend.php";
            $recommends = file_exists($recommend_conf) ? require $recommend_conf : array();
            if (!$recommends)
            {
                $this->show_warning('no_recommends', 'go_back', 'javascript:history.go(-1);', 'set_recommend', 'index.php?app=recommend');
                return;
            }
            $this->assign('recommends', $recommends);
            $this->display('goods.batch.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $recom_id = empty($_POST['recom_id']) ? 0 : intval($_POST['recom_id']);
            if (!$recom_id)
            {
                $this->show_warning('recommend_required');
                return;
            }

            $ids = explode(',', $id);
            
            $data = "";
            foreach ($ids as $key=>$store_id)
            {
                $data .= "('{$recom_id}', '{$store_id}'),";
            }
            $data = substr($data, 0, -1);
            $this->_o2orecommend_mod->db->query("REPLACE INTO wl_o2o_recommend (recom_id,store_id) VALUES $data");
            
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;

            $this->admin_log(Lang::get('goods') . ':' . $id . Lang::get('recommend_to') . ':' . $recommends[$recom_id]);
            $this->show_message('推荐成功', 'back_list', 'index.php?app=storeo2o&page=' . $ret_page, '推荐列表', 'index.php?app=o2orecommend&amp;recom_id=' . $recom_id);
        }
    }
    
    public function drop_uploadedfile()
    {
        $info = array();
        $image_id = isset($_GET['image_id']) ? intval($_GET['image_id']) : 0;
        $image_id && $info = $this->_o2oimage_mod->getCol("select image_url from {$this->_o2oimage_mod->table} where image_id = {$image_id} ");
        if ($info && $this->_o2oimage_mod->drop($image_id))
        {
            $this->_drop_image($info[0]);
            $this->json_result('删除成功');
            return;
        }
        else
        {
            $this->json_error('删除失败');
            return;
        }
    }
    
    public function insert_image()
    {
        $store_id = isset($_GET['store_id']) ? intval($_GET['store_id']) : 0;
        $type = isset($_GET['type']) ? $_GET['type'] : "";
        $image_url = isset($_GET['image_url']) ? $_GET['image_url'] : "";
        $field = "{$type}_image";
        $data[$field] = $image_url;
        
        if($this->_storeo2o_mod->edit($store_id, $data))
        {
            $recom_id = $type == "hot" ? 2 : 1;
            $this->_recommend($recom_id, $store_id);
            $this->json_result('添加成功');
            return;
        }else
        {
            $this->json_error('添加失败');
            return;
        }
    }
    
    private function _recommend($recom_id, $store_id)
    {
        $exist = $this->_o2orecommend_mod->getOne("select 1 from {$this->_o2orecommend_mod->table} where recom_id={$recom_id} AND store_id={$store_id}");
        if(!$exist){
            $this->_o2orecommend_mod->add(array(
                'recom_id' => $recom_id,
                'store_id' => $store_id
            ));
        }
    }

    private function _get_save_data()
    {
        $data = array();
        $data['store_no'] = trim($_POST['store_no']);
        $data['owner_name'] = trim($_POST['owner_name']);
        $data['store_floor'] = trim($_POST['store_floor']);
        $data['tel'] = trim($_POST['tel']);
        $data['qq'] = trim($_POST['qq']);
        $data['email'] = trim($_POST['email']);
        $data['weixin'] = trim($_POST['weixin']);
        $data['enter_time'] = $_POST['enter_time'];
        $data['total_year'] = intval($_POST['total_year']);
        $data['store_url'] = trim($_POST['store_url']);
        $data['exh_id'] = intval($_POST['exh_id']);
        $data['description'] = html_script($_POST['description']);
        
        $data['store_name_search'] = implode('|', $_POST['store_name']);
        $data['products_search'] = implode('|', $_POST['products']);
        
        $data['recommended'] = $data['store_url'] ? 1 : 0;

        return $data;
    }

    private function _get_post_category_ids($cate_ids)
    {
        $result = array();
        if ($cate_ids)
        {
            foreach ($cate_ids as $cate_id => $child)
            {
                if ($child[0])
                {
                    $result[] = $cate_id;
                    $result = array_merge($result, $child);
                }
            }
        }

        if ($result)
        {
            $temp = array_flip($result);
            unset($temp[0]);
            $result = array_flip($temp);
        }

        return $result;
    }

    private function _get_cates_by_store_id($store_id)
    {
        $data = $this->_storeo2o_mod->getRelatedData('has_scategory', $store_id);
        return $this->_make_tree($data);
    }

    private function _get_scategory()
    {
        $data = $this->_scategory_mod->get_list(-1);
        return $this->_make_tree($data);
    }

    private function _get_select_scate($store_id)
    {
        $scates = $this->_get_scategory();
        $select_scates = $this->_get_cates_by_store_id($store_id);
        foreach ($scates as $key => $scate)
        {
            if (isset($select_scates[$key]))
            {
                $scates[$key]['selects'] = $select_scates[$key]['child'];
            }
        }

        return $scates;
    }

    private function _make_tree($data)
    {
        $result = array();
        import('tree.lib');
        $tree = new Tree();

        $tree->setTree($data, 'cate_id', 'parent_id', 'cate_name_' . $this->_language_mod->get_default_lang());
        $scategories = $tree->getArrayList(0);
        foreach ($scategories as $scategory)
        {
            $result[$scategory['id']]['name'] = $scategory['value'];
            foreach ($scategory['children'] as $item)
            {
                $result[$scategory['id']]['child'][$item['id']] = $item['value'];
            }
        }

        return $result;
    }

    private function _drop_storeo2o_image($store_id)
    {
        $info = $this->_o2oimage_mod->getCol("select image_url from {$this->_o2oimage_mod->table} where store_id = {$store_id} ");
        if($info){
            $this->_o2oimage_mod->drop("store_id={$store_id}");
        }
        foreach ($info as $image)
        {
            $this->_drop_image($image);
        }
    }
    
    private function _drop_image($image_url)
    {
        $thumbnail = ROOT_PATH . '/' . dirname($image_url) . '/small/' . basename($image_url);
        $filename = ROOT_PATH . "/" . $image_url;
        if (file_exists($filename))
        {
            @unlink($filename);
        }
        if (file_exists($thumbnail))
        {
            @unlink($thumbnail);
        }
    }

    private function _excel_insert_cate($scates, $store_ids)
    {
        if (!is_array($store_ids))
            $store_ids = array($store_ids);
        $cates_data = array();
        $k = 0;
        foreach ($scates as $key => $vals)
        {
            if ($vals)
                foreach ($vals as $cate_id)
                {
                    $cates_data[$k]['cate_id'] = $cate_id;
                    $cates_data[$k]['store_id'] = $store_ids[$key];
                    $k++;
                }
        }
        if ($cates_data)
        {
            $sql = "insert into wl_category_store (cate_id,store_id) values ";
            foreach ($cates_data as $cate)
            {
                $sql .= "('{$cate['cate_id']}', '{$cate['store_id']}'),";
            }
            $sql = substr($sql, 0, -1);
            $this->_storeo2o_mod->db->query($sql);
        }
    }

//    导入数据时，获取分类cate_id
    private function _excel_get_cate_ids($key, $item, $temp)
    {
        $scates = array();
        for ($i = 10; $i <= 20; $i++)
        {
            if (isset($item[$i]) && $item[$i])
            {
                $parent_cate = $this->_scategory_mod->getCol("select cate_id from wl_scategory where parent_id =0 AND cate_name='{$temp[0][$i]}'");
                if ($parent_cate[0])
                {
                    $scates[$key][] = $parent_cate[0];
                    $cates = explode(',', str_replace("，", ',', $item[$i]));
                    $cates = array_unique($cates);
                    foreach ($cates as $cate_name)
                    {
                        $cate = $this->_scategory_mod->getCol("select cate_id from wl_scategory where parent_id ={$parent_cate[0]} AND cate_name='{$cate_name}'");
                        $cate[0] && $scates[$key][] = $cate[0];
                    }
                }
            }
        }
        return isset($scates[$key]) ? $scates[$key] : array();
    }
    
    public function make_simily_stores()
    {
        set_time_limit(0);
        
        $redis = redis_server();
        
        $stores = $this->_storeo2o_mod->findAll(array(
                        'fields' => 'store_id, products_search',
                        'include' => array(
                                        'has_o2ogoodsimage' => array('fields' => 'image_url', 'index_key' => ''),
                                    ),
        ));
        foreach ($stores as $store_id => $store)
        {
            $arr = array();
            $data = $stores;
            unset($data[$store_id]);
            foreach ($data as $key => $v)
            {
                if($v['o2o_goods_image']){
                    similar_text($store['products_search'], $v['products_search'], $percent);
                    ($percent >= 35) && $arr[$key] = $percent;
                }
            }
            unset($data);
            arsort($arr);
            $arr = array_slice(array_keys($arr), 0, 9);
            if(count($arr) >= 1)
                $redis->hSet("simily", $store_id, json_encode($arr));
        }
        
    }
    
}
